﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace SmallBasicFun.TicTacToeGame
{
	public class TicTacToeUtils
	{
		public static string GetWinner(string emptyCell, Func<int, int, string> getCell)
		{
			var winner = emptyCell;

			winner = GetVictory(winner, (x, y)=>new Point(x, y), getCell, emptyCell);
			winner = GetVictory(winner, (x, y)=>new Point(y, x), getCell, emptyCell);
			winner = GetVictory(winner, (x, y)=>new Point(y, y), getCell, emptyCell);
			winner = GetVictory(winner, (x, y)=>new Point(2 - y, y), getCell, emptyCell);

			return winner;
		}

		private static string GetVictory(string winner, Func<int, int, Point> whichCell, Func<int, int, string> getCell, string emptyCell)
		{
			if (!winner.Equals(emptyCell))
			{
				return winner;
			}

			for (var y = 0; y < 3; y++)
			{
				var list = new List<string>();
				for (int x = 0; x < 3; x++)
				{
					var point = whichCell(x, y);
					list.Add(getCell(point.X, point.Y));
				}
				if (list[0].Equals(list[1]) && list[1].Equals(list[2]) && !list[0].Equals(emptyCell))
				{
					return list[0];
				}
			}
			return emptyCell;
		}
	}
}